package com.ruoyi.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectAccountingQuery;
import com.ruoyi.project.domain.query.ProjectCustomQuery;
import com.ruoyi.project.domain.query.ProjectParticipanQuery;
import com.ruoyi.project.domain.query.ProjectSaleQuery;
import com.ruoyi.project.mapper.ProjectCustomMapper;
import com.ruoyi.project.mapper.ProjectDetailLogMapper;
import com.ruoyi.project.service.IProjectAccountingService;
import com.ruoyi.project.service.IProjectParticipanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/project/accounting")
@Api(tags = "项目信息", description = "项目基本信息")
public class ProjectAccountingController extends BaseController {

    @Resource
    private IProjectAccountingService projectAccountingService;
    @Autowired
    private ProjectCustomMapper projectCustomMapper;

    @Resource
    private ProjectDetailLogMapper projectDetailLogMapper;


    @ApiOperation("列表")
    @GetMapping(value = "/list")
    public R getList(ProjectAccountingQuery query) {
        System.out.println(query);
        return R.ok(projectAccountingService.getList(query));
    }

    @ApiOperation("列表")
    @GetMapping(value = "/checkWait")
    public void checkWait(ProjectAccountingQuery query) {
        System.out.println(query);
      projectAccountingService.checkWait(query);
    }


    @ApiOperation("往来客户的核算列表")
    @GetMapping(value = "/listCustomer")
    public R listCustomer(ProjectAccountingQuery query) {
        System.out.println(query);
        return R.ok(projectAccountingService.listCustomer(query));
    }



    @ApiOperation("获取所有利润计算信息")
    @GetMapping(value = "/allList")
    public R getAllList(ProjectAccountingQuery query) {
        return R.ok(projectAccountingService.getAllList(query.getProjectNo()));
    }


    @ApiOperation("新增")
    @PostMapping(value = "/save")
    public R add(@RequestBody ProjectAccounting project) {
        return R.ok(projectAccountingService.addInfo(project));
    }


    @ApiOperation("修改")
    @PutMapping(value = "/update")
    public R update(@RequestBody ProjectAccounting project) {
        return R.ok(projectAccountingService.updateInfo(project));
    }

    @ApiOperation("重新计算所有信息")
    @PutMapping(value = "/setNewInfo")
    public R setNewInfo(@RequestBody ProjectAccounting project) {
        return R.ok(projectAccountingService.setNewInfo(project,"update"));
    }

    @ApiOperation("修改提交状态")
    @PutMapping(value = "/audit")
    public R audit(@RequestBody ProjectAccounting project) {
        //判断 是吴总就直接设置为总经理已确认的
        //1未提交 2已提交 3已撤回 4总经理已确认
        boolean b = projectAccountingService.updateById(project);
        //往来客户  每审核通过  重新计算更新一下往来的绩效金额 或者驳回
        return R.ok(b);
    }


    @ApiOperation("删除")
    @DeleteMapping(value = "/{id}")
    public R delete(@PathVariable("id") String id) {
        return R.ok(projectAccountingService.deleteInfo(id));
    }


    @ApiOperation("详情")
    @GetMapping(value = "/details")
    public R<ProjectAccounting> getDetails(@RequestParam String id) {
        return R.ok(projectAccountingService.getById(id));
    }


    @ApiOperation("根据项目id获取总成本")
    @GetMapping(value = "/getTotalCost")
    public R getTotalCost(ProjectAccountingQuery query) {
        return R.ok(projectAccountingService.getTotalCost(query));
    }


    @ApiOperation("获取质保金")
    @GetMapping(value = "/warrantyMoney")
    public R warrantyMoney(ProjectAccountingQuery query) {
        return R.ok(projectAccountingService.warrantyMoney(query.getProjectNo()));
    }


    @ApiOperation("获取清单对比")
    @GetMapping(value = "/listCompare")
    public R listCompare(ProjectAccountingQuery query) {
        return R.ok(projectAccountingService.listCompare(query));
    }


    @GetMapping(value = "/getCustomer")
    public R saleInfo(ProjectCustomQuery query) {
        return R.ok(projectAccountingService.saleInfo(query));
    }

    @GetMapping(value = "/saleConfigInfo")
    public R saleConfigInfo(ProjectCustomQuery query) {
        return R.ok(projectAccountingService.saleConfigInfo(query));
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectCustomQuery query) throws IOException {
        Map<String, Object> map = projectAccountingService.saleInfo(query);
        List<ProjectSale> list = (List<ProjectSale>) map.get("saleList");

        // 1. 创建工作簿（.xlsx 格式）
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("出库单数据");

        // 5. 列宽调整（在所有数据写入后处理）
        int[] columnWidths = {
                12 * 256,  // 出库日期（12个字符宽）
                10 * 256,  // 出库数量
                20 * 256,  // 成本单价
                15 * 256,  // 成本合计
                15 * 256,  // 销售售价
                15 * 256,  // 销售总金额
                15 * 256,  // 毛利
                10 * 256,  // 毛利率%
                25 * 256,  // 设备全称
                15 * 256,  // 设备简称
                20 * 256,  // 设备型号
                30 * 256   // 设备参数
        };

        // 3. 定义样式（新增日期样式）
        // 日期格式样式
        CellStyle dateCellStyle = workbook.createCellStyle();
        CreationHelper createHelper = workbook.getCreationHelper();
        dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));

        // 2. 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"出库日期", "出库数量", "成本单价", "成本合计", "销售售价", "销售总金额", "毛利", "毛利率%", "设备全称", "设备简称", "设备型号", "设备参数"};
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
            sheet.autoSizeColumn(i);


            // 先自动调整
            sheet.autoSizeColumn(i);
            // 再根据预设值调整（取自动调整和预设值的较大者）
            int currentWidth = sheet.getColumnWidth(i);
            int presetWidth = columnWidths[i];
            if (presetWidth > currentWidth) {
                sheet.setColumnWidth(i, presetWidth);
            }
            // 设置最大宽度限制（可选）
            if (sheet.getColumnWidth(i) > 40 * 256) {
                sheet.setColumnWidth(i, 40 * 256);
            }
        }

        // 3. 定义样式
        CellStyle highlightStyle = workbook.createCellStyle();
        highlightStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        highlightStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 4. 填充数据
        for (int i = 0; i < list.size(); i++) {
            ProjectSale item = list.get(i);
            Row row = sheet.createRow(i + 1); // 表头在第0行

            // 写入数据
            int colIndex = 0;
            // 写入数据（带空值检查）

            // 出库日期（Date类型）
            Cell dateCell = row.createCell(colIndex++);
            if (item.getSaleDate() != null) {
                dateCell.setCellValue(item.getSaleDate());
                dateCell.setCellStyle(dateCellStyle); // 应用日期样式
            } else {
                dateCell.setCellValue(""); // 空日期显示为空字符串
            }

// 出库数量（Integer类型）
            Cell amountCell = row.createCell(colIndex++);
            if (item.getAmount() != null) {
                amountCell.setCellValue(item.getAmount());
            } else {
                amountCell.setCellValue(""); // 或设为0：amountCell.setCellValue(0);
            }

// 成本单价（String类型）
            Cell costStringCell = row.createCell(colIndex++);
            if (StringUtils.isNotBlank(item.getCostString())) {
                costStringCell.setCellValue(item.getCostString());
            } else {
                costStringCell.setCellValue("");
            }

// 成本合计（BigDecimal类型）
            Cell costTotalCell = row.createCell(colIndex++);
            if (item.getCostTotal() != null) {
                costTotalCell.setCellValue(item.getCostTotal().doubleValue());
            } else {
                costTotalCell.setCellValue(""); // 或设为0：costTotalCell.setCellValue(0);
            }

// 销售售价（BigDecimal类型）
            Cell priceCell = row.createCell(colIndex++);
            if (item.getPrice() != null) {
                priceCell.setCellValue(item.getPrice().doubleValue());
            } else {
                priceCell.setCellValue("");
            }

// 销售总金额（BigDecimal类型）
            Cell totalCell = row.createCell(colIndex++);
            if (item.getTotal() != null) {
                totalCell.setCellValue(item.getTotal().doubleValue());
            } else {
                totalCell.setCellValue("");
            }

// 毛利（BigDecimal类型）
            Cell profitCell = row.createCell(colIndex++);
            if (item.getProfit() != null) {
                profitCell.setCellValue(item.getProfit().doubleValue());
            } else {
                profitCell.setCellValue("");
            }

// 毛利率%（BigDecimal类型）
            Cell profitRatioCell = row.createCell(colIndex++);
            if (item.getProfitRatio() != null) {
                profitRatioCell.setCellValue(item.getProfitRatio().doubleValue());
            } else {
                profitRatioCell.setCellValue("");
            }

// 设备全称（String类型）
            Cell fullNameCell = row.createCell(colIndex++);
            if (StringUtils.isNotBlank(item.getFullName())) {
                fullNameCell.setCellValue(item.getFullName());
            } else {
                fullNameCell.setCellValue("");
            }

// 设备简称（String类型）
            Cell nameCell = row.createCell(colIndex++);
            if (StringUtils.isNotBlank(item.getName())) {
                nameCell.setCellValue(item.getName());
            } else {
                nameCell.setCellValue("");
            }

// 设备型号（String类型）
            Cell modalCell = row.createCell(colIndex++);
            if (StringUtils.isNotBlank(item.getModal())) {
                modalCell.setCellValue(item.getModal());
            } else {
                modalCell.setCellValue("");
            }

// 设备参数（String类型）
            Cell paramCell = row.createCell(colIndex++);
            if (StringUtils.isNotBlank(item.getParam())) {
                paramCell.setCellValue(item.getParam());
            } else {
                paramCell.setCellValue("");
            }

            // 如果 status == "1"，整行设置为浅黄色
            if ("1".equals(item.getStatus())) {
                for (int j = 0; j < headers.length; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        cell = row.createCell(j);
                    }
                    cell.setCellStyle(highlightStyle);
                }
            }
        }


        // 5. 添加统计行（最后一行）
        int lastRowNum = sheet.getLastRowNum();
        Row statRow = sheet.createRow(lastRowNum + 1);

        // 遍历所有列，仅对 isStatistics=true 的列进行统计
        for (int col = 0; col < headers.length; col++) {
            Cell cell = statRow.createCell(col);

            // 检查当前列是否需要统计（根据注解判断）
            boolean needStat = false;
            switch (col) {
                case 1:  // 出库数量 (amount)
                case 3:  // 成本合计 (costTotal)
                case 5:  // 销售总金额 (total)
                case 6:  // 毛利 (profit)
                    needStat = true;
                    break;
            }

            if (needStat) {
                // 计算该列的总和
                double sum = 0;
                for (int rowNum = 1; rowNum <= lastRowNum; rowNum++) {
                    Row row = sheet.getRow(rowNum);
                    if (row != null) {
                        Cell valueCell = row.getCell(col);
                        if (valueCell != null && valueCell.getCellType() == CellType.NUMERIC) {
                            sum += valueCell.getNumericCellValue();
                        }
                    }
                }
                cell.setCellValue(sum);
                cell.setCellStyle(getStatCellStyle(workbook)); // 设置统计行样式
            } else {
                if (col == 0) {
                    cell.setCellValue("合计");
                }
            }
        }

        // 6. 设置响应头并写入 Excel
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=出库单数据.xlsx");

        String filename = "出库单数据.xlsx";
        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename);

        workbook.write(response.getOutputStream());
        workbook.close();
    }


    // 统计行样式（灰色背景，加粗）
    private CellStyle getStatCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }


    @ApiOperation("获取管家婆出库单，往来客户菜单")
    @GetMapping(value = "/saleListCustomer")
    public R<TableDataInfo> saleListCustomer(ProjectSaleQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ProjectSale> list = projectAccountingService.getAllGjpListCustomer(query);
        return R.ok(new TableDataInfo(list, page.getTotal()));
    }


}
